package com.huanxing.cloud.auth.controller;

import cn.hutool.core.util.StrUtil;
import com.huanxing.cloud.common.core.entity.Result;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * token
 *
 * @author lijx
 * @since 2022/2/10 16:25
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/token")
public class TokenController {
  private final TokenStore tokenStore;
  /**
   * 用户退出
   *
   * @author lijx
   * @date 2022/5/3 20:46
   * @version 1.0
   */
  @DeleteMapping("/logout")
  public Result<?> logout(
      @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {
    if (StrUtil.isBlank(authHeader)) {
      return Result.success("退出失败，token 为空", null);
    }
    String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StrUtil.EMPTY).trim();
    OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
    if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) {
      return Result.success("退出失败，token 无效", null);
    }
    // 清空access token
    tokenStore.removeAccessToken(accessToken);

    // 清空 refresh token
    OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
    tokenStore.removeRefreshToken(refreshToken);
    return Result.success();
  }
}
